import { App } from 'vue';
import { createRouter, RouteRecordRaw, createWebHistory } from 'vue-router';
import { RedirectRoute } from '@/router/base';
import { PageEnum } from '@/enums/pageEnum';
import { createRouterGuards } from './router-guards';

const modules = import.meta.globEager('./modules/**/*.ts');

const routeModuleList: RouteRecordRaw[] = [];

Object.keys(modules).forEach((key) => {
  // @ts-ignore
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

function sortRoute(a, b) {
  return (a.meta?.sort || 0) - (b.meta?.sort || 0);
}

routeModuleList.sort(sortRoute);

export const RootRoute: RouteRecordRaw = {
  path: '/',
  name: 'Root',
  redirect: PageEnum.BASE_HOME,
  meta: {
    title: 'Root',
  },
};

export const LoginRoute: RouteRecordRaw = {
  path: '/login',
  name: 'Login',
  component: () => import('@/views/login/index.vue'),
  meta: {
    title: '登录',
  },
};

export const ForgetPwdRoute: RouteRecordRaw = {
  path: '/forget/:email?/:code?',
  name: 'Forget',
  component: () => import('@/views/forgetPassword/index.vue'),
  meta: {
    title: '找回密码',
    ignoreAuth: true
  },
}

export const RegisterRoute: RouteRecordRaw = {
  path: '/register',
  name: 'Register',
  component: () => import('@/views/register/index.vue'),
  meta: {
    title: '注册',
    ignoreAuth: true
  },
}

export const FilesRoute: RouteRecordRaw = {
  path: '/files',
  name: 'Files',
  component: () => import('@/views/worker/fileSystem/index.vue'),
  meta: {
    title: '文件系统',
    ignoreAuth: true
  },
}

export const MdPreviewRoute: RouteRecordRaw = {
  path: '/mdPreview/:id',
  name: 'MdPreview',
  component: () => import('@/views/mdPreview/preview.vue'),
  meta: {
    title: 'Markdown预览',
    ignoreAuth: true
  },
}

export const VerifyRouter: RouteRecordRaw = {
  path: '/verify/:type/:data/:code',
  name: 'Verify',
  component: () => import('@/views/verify/VerifyWhitePage.vue'),
  meta: {
    title: '核实页',
    ignoreAuth: true
  },
}

export const ResultRouter: RouteRecordRaw = {
  path: '/result',
  name: 'Result',
  component: () => import('@/views/result/result.vue'),
  meta: {
    title: '操作结果',
    ignoreAuth: true
  },
}

//需要验证权限
export const asyncRoutes = [...routeModuleList];

//普通路由 无需验证权限
export const constantRouter: any[] = [
  LoginRoute, RootRoute, RedirectRoute,
  RegisterRoute, ForgetPwdRoute, FilesRoute,
  MdPreviewRoute, ResultRouter, VerifyRouter,
];

const router = createRouter({
  history: createWebHistory(''),
  routes: constantRouter,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

export function setupRouter(app: App) {
  app.use(router);
  // 创建路由守卫
  createRouterGuards(router);
}

export default router;
